/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package am.aua.renju.databaseaccess;

import am.aua.renju.entity.MoveHistory;
import am.aua.renju.entity.SecurityQuestion;
import java.util.List;
import javax.persistence.*;

/**
 *
 * @author ara
 */
public class Operations implements IOperations {

    static Operations instance;
    private EntityManagerFactory emf;

    public static IOperations getInstance() {
        if (instance == null) {
            instance = new Operations();
        }
        return instance;
    }

    private Operations() {
        emf = Persistence.createEntityManagerFactory("RenjuDPU");
    }

    @Override
    public List<SecurityQuestion> getSecurityQuestins() {
        EntityManager em = emf.createEntityManager();
        TypedQuery<SecurityQuestion> questionsQuery = em.createNamedQuery("SecurityQuestion.findAll",
                SecurityQuestion.class);

        List<SecurityQuestion> securityQuestions = questionsQuery.getResultList();
        em.close();
        return securityQuestions;
    }

    @Override
    public List<MoveHistory> getMoveHistory(int gameId) {
        EntityManager em = emf.createEntityManager();
        TypedQuery<MoveHistory> query = em.createQuery("SELECT mh FROM MoveHistory mh WHERE gameId=:gameId", MoveHistory.class).
                setParameter("gameId", gameId);
        List<MoveHistory> result = query.getResultList();
        em.close();
        return result;

    }

    @Override
    public void createMoveHistory(MoveHistory moveHistory) {
        EntityManager em = emf.createEntityManager();
        EntityTransaction et = em.getTransaction();
        et.begin();
        em.persist(moveHistory);
        et.commit();
        em.close();
    }

    @Override
    public SecurityQuestion getSecurityQuestionByQuestionString(String text) {
        EntityManager em = emf.createEntityManager();
        TypedQuery<SecurityQuestion> query = em.createNamedQuery("SecurityQuestion.findByQuestionString", SecurityQuestion.class).
                setParameter("questionString", text);
        SecurityQuestion result;
        try {
            result = query.getSingleResult();
        } catch (NoResultException ex) {
            return null;
        } finally {
            em.close();
        }
        return result;
    }

    @Override
    public void close() {
        if (emf.isOpen()) {
            emf.close();
        }
        Operations.instance = null;
    }
}
